/**
 * @name: 公共方法
 */
export const getObjType = (obj) => {
  var toString = Object.prototype.toString
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  }
  if (obj instanceof Element) {
    return 'element'
  }
  return map[toString.call(obj)]
}
// 对象深拷贝
export const deepClone = (data) => {
  var type = getObjType(data)
  var obj
  if (type === 'array') {
    obj = []
  } else if (type === 'object') {
    obj = {}
  } else {
    //不再具有下一层次
    return data
  }
  if (type === 'array') {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]))
    }
  } else if (type === 'object') {
    for (var key in data) {
      obj[key] = deepClone(data[key])
    }
  }
  return obj
}
// Base64字符串转换为Blob对象
export const base64ToBlob = (base64, contentType) => {
  const byteCharacters = atob(base64.split(',')[1])
  const byteNumbers = new Array(byteCharacters.length)
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i)
  }
  const byteArray = new Uint8Array(byteNumbers)
  return new Blob([byteArray], {
    type: contentType
  })
}
// 使用Blob对象创建File对象
export const blobToFile = (blob, fileName) => {
  return new File([blob], fileName, {
    type: blob.type,
    lastModified: Date.now()
  })
}
// 获取url参数
export const getUrlParams = (urlParams, key) => {
  if (typeof urlParams === 'string') {
    let params = new URLSearchParams(urlParams).get(key)
    return params
  } else {
    return null
  }
}

// 获取token
export const getRealToken = () => {
  let splitUrl = window.location.href.split('?')
  let searchParam = splitUrl && splitUrl.length >= 2 ? splitUrl[1] : null
  let urlToken =
    searchParam && getUrlParams(searchParam, 'token')
      ? getUrlParams(searchParam, 'token')
      : getUrlParams(searchParam, 'access_token')
  const currentUser = sessionStorage.getItem('currentUser')
    ? JSON.parse(sessionStorage.getItem('currentUser'))
    : null
  let frontTokenKey = {
    insightToken:
      currentUser && currentUser.token ? currentUser.token : urlToken,
    isCheckOut: getUrlParams(searchParam, 'access_token') ? true : false
  }
  if (urlToken != null && urlToken != '') {
    frontTokenKey.insightToken = urlToken
  } else if (currentUser != null) {
    frontTokenKey.insightToken = currentUser.token
  }
  return frontTokenKey
}

export const getAccessToken = () => {
  let splitUrl = window.location.href.split('?')
  let searchParam = splitUrl && splitUrl.length >= 2 ? splitUrl[1] : null
  let urlToken =
    searchParam && getUrlParams(searchParam, 'token')
      ? getUrlParams(searchParam, 'token')
      : getUrlParams(searchParam, 'access_token')
  return urlToken
}
